<?php

namespace App\Http\Controllers;

use App\Libs\CommonUtils;
use App\Models\UserTeam;
use App\Models\Volunteer;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class VolunteerBlacklistController extends Controller
{
    public function blacklist(Request $request) {
        $perPage = $request->get('perPage', 10);
        $keyword = $request->get('keyword', '');
        $user = $request->user();

        $query = DB::table('volunteer')
            ->leftjoin('user','user.id', '=', 'volunteer.user_id')
            ->where('volunteer.in_blacklist', '=', 1);

        switch($user->type)
        {
            case 2:
                $query = $query->leftjoin('user_team','user_team.user_id', '=', 'volunteer.user_id')
                    ->where('user_team.team_id', '=', $user->team_id)
                    ->where('user_team.verify_status', '=', 1);
                break;
            case 3:
                $query = $query->where('volunteer.org_id', '=', $user->org_id);
                break;
        }

        if ($user->type == 4 && $request->has('org_id')) {
            $query = $query->where('volunteer.org_id', '=', $request->get('org_id'));
        }

        $query = $query->select('volunteer.*', 'user.username','user.avatars');

        if(!empty($keyword))
        {
            $query = $query->where(function($query) use ($keyword){
                $query->where('volunteer.phone', 'like', "%{$keyword}%")
                    ->orwhere('volunteer.real_name', 'like', "%{$keyword}%")
                    ->orWhere('volunteer.id_number', 'like', "%{$keyword}%")
                    ->orWhere('user.username', 'like', "%{$keyword}%");
            });
        }

        if ($request->has('team_id')) {
            $userIds = [];
            foreach (UserTeam::where('team_id', '=', $request->get('team_id'))->select('user_id')->get()->toArray() as $item) {
                $userIds[] = $item['user_id'];
            }
            $query->whereIn('user.id', $userIds);
        }

        $query->orderby('volunteer.id', 'asc');
        $data = null;

        $data = $query->paginate($perPage)->toArray();
//        Log::info($data['total']);

        /**  这里就是 用groupby实现查找需要user_id的project_count 但这方法有个问题，查找user_id如果在user_project表中没有记录将不会进行匹配*/
        $ids = array_map(function($item){
            // 将project_count 设为0
            $item->project_count = 0;
            $item->good_at = [];
            // 根据身份证 计算年龄
            if(!empty($item->id_number) && CommonUtils::isIdCard($item->id_number)){
                $item->age = CommonUtils::get_age($item->id_number);
                $item->sex = CommonUtils::get_sex($item->id_number);
            } else if (!empty($item->birthday)){
                $item->age = intval(date('Y')) - intval(explode('-',$item->birthday)[0]) + 1;
            }
            return $item->user_id;
        },$data['data']);
        $projectInfo=DB::table('user_project')->select(DB::raw('count(*) as project_count'), 'user_id')
            ->whereIn('user_id', $ids)->where('verify_status', '=', 1)
            ->groupby('user_id')->orderby('user_id')->get()->toArray();

        $teamList = array();

        foreach (UserTeam::whereIn('user_id', $ids)->where('verify_status', '=', '1')->with('team')->get() as $userTeam) {
            if (!isset($teamList[$userTeam->user_id])) {
                $teamList[$userTeam->user_id] = array();
            }

            if (!$userTeam->team) {
                continue;
            }

            $teamList[$userTeam->user_id][] = [
                'name' => $userTeam->team->name,
                'id' => $userTeam->team->id,
                'org_id' => $userTeam->team->org_id
            ];
        }

//        $projectInfoMap = [];
//        foreach ($projectInfo as $pro) {
//            $projectInfoMap[$pro->user_id] = $pro;
//        }

        $goodAt = DB::table('volunteer_good_at')->select('user_id', 'good_at_name')
            ->whereIn('user_id', $ids)->orderby('user_id')->get()->toArray();

        for($j = 0;$j<count($data['data']);$j++) {
            $item = $data['data'][$j];
            $item->team = isset($teamList[$item->user_id]) ? $teamList[$item->user_id] : [];

            for ($i = 0; $i < count($projectInfo); $i++) {
                if ($data['data'][$j]->user_id == $projectInfo[$i]->user_id) {
//                    Log::info($projectInfo[$i]->project_count);
                    $data['data'][$j]->project_count = $projectInfo[$i]->project_count;
                }
            }
            for ($i = 0; $i < count($goodAt); $i++) {
                if ($data['data'][$j]->user_id == $goodAt[$i]->user_id) {
//                    Log::info($data['data'][$j]->good_at);
                    array_push($data['data'][$j]->good_at, $goodAt[$i]->good_at_name);
                }
            }
        }

        $res = $data['data'];


        return $this->returnJSON([
            'count' => $data['total'],
            'rows' => $res
        ]);
    }

    public function unblack(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = Volunteer::whereIn('user_id',  $ids)->update(['in_blacklist' => 0]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '移除黑名单成功');
        } else {
            return $this->returnJSON(null, 1, "移除黑名单失败");
        }
    }
    public function black(Request $request, $id)
    {
        $this->validate($request, [
            'reason' => 'required'
        ]);

        $now = new Carbon();

        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = Volunteer::whereIn('user_id',  $ids)->update([
            'in_blacklist' => 1,
            'black_reason' => $request->get('reason'),
            'blacked_at' => $now->toDateTimeString()
        ]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '拉黑成功');
        } else {
            return $this->returnJSON(null, 1, "拉黑失败");
        }
    }
}
